<template>
  <AppPage class="bg-[#f8f8f8]" article-class="" header-class="bg-[#3d8ffd]">
    <template #center>
      <span class="c-white">订单填写</span>
    </template>
    <div class="pb-70 info_container">
      <div class="px-15 mt-15">
        <div class="rounded-6 bg-white px-10 pt-12">
          <div class="c-[#333] text-15 pb-10">{{ route.query.product_name}}</div>
          <div class="c-[#333] text-15 pb-10 flex items-center">
            <span class="c-[#656565] text-14 mr-6">预计出行时间</span>
            <div class="flex items-center" @click="selectTravelTime">
              <span class="c-[#333] text-14 mr-6">{{ basicData.travelTime?basicData.travelTime:'请选择出行时间'}}</span>
              <Edit color="#3d8ffd" size="1-0" />
            </div>
          </div>
        </div>
        <div class="px-4 bg-white pb-2">
          <div class="rounded-6 bg-[#f8f9fb] px-10 py-12">
            <div class="c-[#333] text-14 pb-10">最晚在<span class="theme-color">{{ basicData.travelTime&&sevenDayBefore(basicData.travelTime) }}</span>收集资料，请合理安排时间</div>
            <div class="c-[#333] text-13 pb-10">自签发起生效，请再有效期内入境！</div>
          </div>
        </div>
      </div>
      <div class="px-15  mb-12">
        <div class="bg-white">
          <nut-form label-width="60">
            <div class="flex items-center justify-between py-10">
              <h3 class="px-12  text-14">申请人信息</h3>
              <div class="px-12 flex items-center" @click="addApplicantPeople">
                <Plus color="#3d8ffd" size="20" />
                <span class="ml-2 text-14">添加申请人信息</span>
              </div>
            </div>
            <div class="pb-5" v-if="applicantPeopleList.length">
              <nut-form-item label-width="60" required label="姓名" v-for="(item, i) in applicantPeopleList" :key="i">
                <div class="relative">
                  <nut-input v-model="item.applicant_name" class="nut-input-text" placeholder="请输入姓名" type="text" />
                  <div class="absolute right-10 top--5 w-100">
                    <selectIdentity v-model:value="item.identity_id" v-model:text="item.identity_name" :columns="identityTYpeColumns" />
                  </div>
                  <div class="absolute top-0 right--10" @click="minusApplicantPeople(i)">
                    <Del color="#999" />
                  </div>
                </div>
              </nut-form-item>
            </div>
          </nut-form>
        </div>
      </div>
      <div class="px-15 mb-12">
        <nut-form>
          <div class="flex items-center justify-between">
            <h3 class="px-12 pt-10 text-14">联系人信息</h3>
          </div>
          <nut-form-item label="姓名" required>
            <nut-input v-model="basicData.contact_name" class="nut-input-text" placeholder="请输入姓名" type="text" />
          </nut-form-item>
          <nut-form-item label="联系电话" required>
            <nut-input v-model="basicData.contact_number" class="nut-input-text" placeholder="请输入联系电话" type="text" />
          </nut-form-item>
        </nut-form>
      </div>
      <div class="px-15 mb-12">
        <nut-form>
          <h3 class="px-12 pt-10 text-14">收件人信息</h3>
          <nut-form-item label="姓名" required>
            <nut-input v-model="orderExpressAddress.addressee" class="nut-input-text" placeholder="请输入姓名" type="text" />
          </nut-form-item>
          <nut-form-item label="联系电话" required>
            <nut-input v-model="orderExpressAddress.mobile_phone" class="nut-input-text" placeholder="请输入联系电话" type="text" />
          </nut-form-item>
          <provinceCityCounty v-model:province_code="orderExpressAddress.province_code" v-model:city_code="orderExpressAddress.city_code" v-model:county_code="orderExpressAddress.county_code" />
          <nut-form-item label="地址" required>
            <nut-input v-model="orderExpressAddress.detail_address" class="nut-input-text" placeholder="请输入地址" type="text" />
          </nut-form-item>
        </nut-form>
      </div>
      <div class="px-15 mb-12">
        <div class="bg-white rounded-6 px-12 pb-12">
          <h3 class="pt-10 text-15 pb-6 font-600">其他</h3>
          <div class="flex items-center justify-between  rounded-6" @click="openVidaExpirePopup">
            <div>
              <span class="text-13 c-[#000]">签证生效日期</span>
            </div>
            <div class="flex items-center">
              {{  basicData.effect_date?basicData.effect_date:'请签证生效日期' }}
              <Right width="12" class="relative top--1" color="#999" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="w-full px-15 box-border fixed bottom-0 left-0  bg-white py-15">
      <div class="w-full  box-border" @click="createOrder">
        <nut-button :block="true" type="info">立即支付</nut-button>
      </div>
    </div>
  </AppPage>
  <datePick ref="selectDateTime" v-model:value="basicData.travelTime" />
  <datePick ref="selectVidaExpireTime" v-model:value="basicData.effect_date" />
  <!-- <payPopup @toPay="toPay" ref="payWayPop" :payAccount="pay_amount" :orderNo="orderNo" @closePay="toOrderDetail" /> -->
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import { showToast } from '@nutui/nutui';
import '@nutui/nutui/dist/packages/toast/style';
import { Edit, Plus, Del, Right } from '@nutui/icons-vue';
import { getProvinceAddress, addOrder, productPriceQuery } from '@/api/visa'
import { useRoute, useRouter } from 'vue-router'
import datePick from '@/components/datePick/index.vue'
import selectIdentity from '@/components/select/select.vue'
import provinceCityCounty from '@/components/provinceCityCounty/index.vue'
import payPopup from '@/components/payPopup/index.vue'
import { getOrderDetail } from '@/api/visa'
import { identityTYpeColumns } from '@/utils/type/visa.js'
import { sevenDayBefore } from '@/utils/common/common.js'
import { isEmpty } from '@/utils/common/is.js'
import { useVisaStore } from '@/store/modules/visa/index.js'
import { useUserStore } from '@/store/modules/user/index.js'
import axios from "axios";
const route = useRoute()
const router = useRouter()
const basicData = reactive({
  travelTime: '2023-12-12',
  contact_name: 'zhonhai',
  contact_number: '18126495952',
  address: ''
})
basicData.travelTime = route.query.travelTime
const orderExpressAddress = reactive({
  addressee: 'donmin',
  mobile_phone: '18126475753',
  province_code: '',
  city_code: '',
  detail_address: '',
})

let applicantPeopleList = ref([
  { applicant_name: 'zhonhai', identity_id: 0, identity_name: '在职人员' }
])
// 选择不同职业 
const addApplicantPeople = () => {
  applicantPeopleList.value.push({ applicant_name: '', identity_id: '' })
}
const minusApplicantPeople = (index) => {
  applicantPeopleList.value.splice(index, 1)
}

const getProvinceAddressFun = async () => {
  const result = await getProvinceAddress()
  let { data, code } = result
  let useVisa = useVisaStore()
  if (+code === 200) {
    if (data.length) {
      let revertFun = (arr) => {
        if (arr.length) {
          arr.forEach((item) => {
            item.id = item.key
            item.name = item.value
            if (item.subList && item.subList.length) {
              item.children = revertFun(item.subList)
            }
          })
        }
        return arr
      }
      useVisa.setAddressList(revertFun(data))
    }
  }
}

let orderNo = ref('')
const payWayPop = ref()
const openPayPopup = async () => {
  payWayPop.value.open()
}


// 开始获取订单号并支付
let payNum = 0
let initSearchPayStatusNum = 40
let searchPayStatusNum = initSearchPayStatusNum
let pay_amount = ref(route.query.pay_amount)
const createOrder = async () => {
  payNum++
  let applicant_set = []
  if (!applicantPeopleList.value.length) {
    showToast.text('请添加申请人');
    return
  }
  let _isEmptyApplicant_name = applicantPeopleList.value.some((item) => {
    return isEmpty(item.applicant_name)
  })
  let _isEmptyIdentity_id = applicantPeopleList.value.some((item) => {
    return isEmpty(item.identity_name)
  })

  if (_isEmptyApplicant_name) {
    showToast.text('请输入申请人姓名');
    return
  }
  if (_isEmptyIdentity_id) {
    showToast.text('请选择申请人身份');
    return
  }

  if (isEmpty(basicData.contact_name)) {
    showToast.text('请添加联系人姓名');
    return
  }
  if (isEmpty(basicData.contact_number)) {
    showToast.text('请添加联系人联系方式');
    return
  }

  if (isEmpty(orderExpressAddress.addressee)) {
    showToast.text('请添加收件人姓名');
    return
  }
  if (isEmpty(orderExpressAddress.mobile_phone)) {
    showToast.text('请添加联系人联系方式');
    return
  }
  if (isEmpty(orderExpressAddress.province_code) || isEmpty(orderExpressAddress.city_code) || isEmpty(orderExpressAddress.county_code)) {
    showToast.text('请添加联系人省市区');
    return
  }
  if (isEmpty(orderExpressAddress.detail_address)) {
    showToast.text('请添加联系人详细地址');
    return
  }

  applicantPeopleList.value.forEach(item => {
    applicant_set.push({
      applicant_no: useUserStore().uId,
      applicant_name: item.applicant_name,
      identity_id: item.identity_id
    })
  })

  let params = {
    product_id: route.query.product_id,
    product_name: route.query.product_name,
    contact_number: basicData.contact_number,
    contact_name: basicData.contact_name,
    pay_amount: pay_amount.value,
    depart_date: basicData.travelTime,
    effect_date: basicData.effect_date,
    order_express_address: {
      addressee: orderExpressAddress.addressee,
      mobile_phone: orderExpressAddress.mobile_phone,
      detail_address: orderExpressAddress.detail_address,
      province_code: orderExpressAddress.province_code,
      city_code: orderExpressAddress.city_code,
      county_code: orderExpressAddress.county_code
    },
    // applicant_set: JSON.stringify(applicant_set)
    applicant_set: applicant_set
  }
  const { data, code } = await addOrder(params)
  if (+code === 200) {
    // openPayPopup()
    orderNo.value = data.somytrip_order_id
    let userInfo = useUserStore().userInfo
    if (userInfo.source === 'applet') {
      searchPayStatusNum = initSearchPayStatusNum
      let callback = encodeURIComponent('searchOrderPayStatus()');
      window.SMTJSApi && SMTJSApi.postMessage(`pay?orderNo=${data.somytrip_order_id}&callback=${callback}`);
    } else if (userInfo.source === 'wechat.application') {

    }
    // searchOrderPayStatus()
  } else if (+code === 300) {
    const { code, data } = await productPriceQuery(params.product_id)
    if (+code !== 200) return
    pay_amount.value = data.price
    if (pay_amount && payNum < 3) {
      createOrder()
    }
  }
}

// const toOrderDetail = () => {
//   router.push({ path: '/orderDetail', query: params })
// }

const selectDateTime = ref('')
const selectTravelTime = () => {
  selectDateTime.value.open()
}
const toOrderDetail = () => {
  let params = {
    orderNo: orderNo.value,
    // productName: '暂定美国签证数据固定的'
  }
  router.push({ path: '/orderDetail', query: params })
}

const selectVidaExpireTime = ref('')
const openVidaExpirePopup = () => {
  selectVidaExpireTime.value.open()
}

const searchOrderPayStatus = async () => {
  searchPayStatusNum--
  const _orderNo = orderNo.value
  const { code, data } = await getOrderDetail(_orderNo)
  if (+code === 200) {
    const pay_status = data.order_info.pay_status
    if (+pay_status === 2) {
      toOrderDetail()
    } else if (+pay_status === 0) {
      setTimeout(() => {
        if (searchPayStatusNum <= 0) return
        searchOrderPayStatus()
      }, 3000);
    }
  }
}

onMounted(async () => {
  await getProvinceAddressFun()
  // 将tt方法绑定到window下面，提供给外部调用
  window['searchOrderPayStatus'] = () => {
    searchOrderPayStatus()
  }
})
</script>
<style scoped>
.card-tabs .n-tabs-nav--bar-type {
  padding-left: 4px;
}
</style>
<style lang="scss" scoped>
.city {
  line-height: 32px;
  border: 1px solid #ddd;
}
.city.active {
  line-height: 32px;
  border: 1px solid #f00;
}
</style>
<style>
.info_container .nut-cell {
  padding: 10px 13px;
}
.info_container .nut-cell__title {
  flex: none;
}
</style>